<?php

namespace app\actions;

use app\components\UserListEvent;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\db\ActiveQuery;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\View;

class UserList extends BaseUserAction {

    public $with = [];
    public $where = [];
    public $title = '';
    public $layout;
    public $_view;
    public $sort = SORT_DESC;
    public $orderBy = '';
    public $ajaxRegisterPagination = FALSE;

    public function run() {
        /* @var $modelClass \app\components\BaseActiveRecord */
        $modelClass = $this->modelClass;
        $query = $modelClass::find();
        if (!empty($this->where) && is_array($this->where)) {
            $query->filterWhere($this->where);
        }
        if (!empty($this->where) && is_string($this->where)) {
            $query->where($this->where);
        }
        if (!empty($this->orderBy)) {
            $query->orderBy($this->orderBy);
        }

        $query->with = $this->with;

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => ['attributes' => ['id'], 'defaultOrder' => ['id' => $this->sort]],
            'pagination' => FALSE !== $this->pageSize ? ['defaultPageSize' => $this->pageSize] : FALSE,
        ]);
        $models = $dataProvider->getModels();
        $pagination = $dataProvider->getPagination();

        $view = NULL === $this->_view ? $this->id : $this->_view;
        $view = $this->controller->isAjax() ? "{$view}_ajax" : $view;

        $this->registerPagination($pagination);
        return $this->render(compact('models'), $view);
    }

    public function registerPagination($pagination) {
        if (FALSE !== $this->pageSize) {
            if ($this->controller->isAjax() && !$this->ajaxRegisterPagination) {
                return;
            }
            /* @var $pagination Pagination */
            $params = \Yii::$app->request->getQueryParams();
            $params['page'] = '$page';
            $params[0] = '';

            $json_page = Json::encode([
                'pageCount' => $pagination->getPageCount(),
                'pageUrl' => Url::to($params)
            ]);
            $this->controller->view->registerJs("window.pager = {$json_page};", View::POS_HEAD);
        }
    }

    protected function toArray($models, $filed, $data = array()) {
        foreach ($models as $model) {
            $data[$model[$filed]] = $model[$filed];
        }
        return $data;
    }
}